package main

import (
	"fmt"
	"sync"
	"time"
)

var num int
var wait sync.WaitGroup
var adder_lock sync.Mutex

func add() {
	// 谁先抢到了这把锁，谁就把它锁上，一旦锁上，其他的线程就只能等着
	adder_lock.Lock()

	for i := 0; i < 1000000; i++ {
		num++

	}
	adder_lock.Unlock()

	wait.Done()
}
func reduce() {
	adder_lock.Lock()

	for i := 0; i < 1000000; i++ {
		num--

	}
	adder_lock.Unlock()

	wait.Done()
}

func timer(foo func()) func() time.Duration {
	return func() time.Duration {
		s := time.Now()
		foo()
		duration := time.Now().Sub(s)
		return duration
	}
}

func main() {
	t := timer(func() {
		wait.Add(2)
		go add()
		go reduce()
		wait.Wait()
		fmt.Println(num)
	})()
	fmt.Printf("t: %v\n", t)

}
